package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.sys.modular.system.entity.BtyBorrower;
import cn.stylefeng.guns.sys.modular.system.entity.Dict;
import cn.stylefeng.guns.sys.modular.system.entity.MeiTuan;
import cn.stylefeng.guns.sys.modular.system.model.weixin.TemplateData;
import cn.stylefeng.guns.sys.modular.system.model.weixin.WechatTemplate;
import cn.stylefeng.guns.sys.modular.system.service.BtyBankService;
import cn.stylefeng.guns.sys.modular.system.service.BtyBorrowerService;
import cn.stylefeng.guns.sys.modular.system.service.DictService;
import cn.stylefeng.guns.sys.modular.system.service.MeiTuanService;
import cn.stylefeng.guns.sys.modular.system.warpper.NoticeWrapper;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/weiXinApi")
public class APIController {

    private String PREFIX = "/modular/system/";

    @Autowired
    private BtyBankService btyBankService;
    @Resource
    private DictService dictService;
    @Autowired
    private BtyBorrowerService btyBorrowerService;
    @Autowired
    private MeiTuanService meiTuanService;

    /**
     * 跳转到api
     */
    @RequestMapping()
    public String noticeUpdate(ModelMap model) {
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }
        //String openid = "oaLVF5ktggE4Dy0Q9eD_-xIQpjRk";
        //String openid = "oM18PwW_aRtOaOH0F-YwsmMxT2sM";
        //String openid = "oM18PwQBM_f-4xlF7DKwnLQZ7XXc";
        //String openid = "oM18PwZuWBwyz9UEaZgxJa-sxi9w";
        String openid = "oM18PwWQsdIP3QEKcWejL1tF3X8s";
        // 发送模板消息
        //String resultUrl2 = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        // 封装基础数据
        WechatTemplate wechatTemplate = new WechatTemplate();
        wechatTemplate.setTemplate_id("AC2qeKbnrgkutEWWh8nb9C73v8uA1dVa5Np8ckE5PzA");
        wechatTemplate.setTouser(openid);
        Map<String, TemplateData> mapdata = new HashMap<>();
        // 封装模板数据
        TemplateData first = new TemplateData();
        first.setValue("抱歉，您的订单无法为您配送");
        first.setColor("#173177");
        mapdata.put("first", first);

        TemplateData keyword1 = new TemplateData();
        keyword1.setValue("2020-08-28 16:01:56");//user.getMobile()
        first.setColor("#173177");
        mapdata.put("keyword1", keyword1);

        TemplateData keyword2 = new TemplateData();
        keyword2.setValue("23元");
        first.setColor("#173177");
        mapdata.put("keyword2", keyword2);

        TemplateData keyword4 = new TemplateData();
        keyword4.setValue("红咖喱牛肉 x 1份");
        first.setColor("#173177");
        mapdata.put("keyword3", keyword4);

        TemplateData keyword5 = new TemplateData();
        keyword5.setValue("已取消");
        first.setColor("#173177");
        mapdata.put("keyword4", keyword5);

        TemplateData keyword6 = new TemplateData();
        keyword6.setValue("菜品已卖光");
        first.setColor("#173177");
        mapdata.put("keyword5", keyword6);


        TemplateData keyword3 = new TemplateData();
        keyword3.setValue("请您预订其他菜品或联系客服>>");
        keyword3.setColor("#173177");
        mapdata.put("remark", keyword3);
        wechatTemplate.setData(mapdata);
        //RestTemplate restTemplate = new RestTemplate();
        String userMsg = "https://api.weixin.qq.com/cgi-bin/user/info?openid=" + openid + "&lang=zh_CN&access_token=" + accessToken;
        String userForm = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
        String formWorkMsg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        RestTemplate restTemplate = new RestTemplate();
        String userMsgS = restTemplate.getForObject(userMsg, String.class);
        String userFormS = restTemplate.getForObject(userForm, String.class);
        JSONObject weiMsg = (JSONObject) JSONObject.toJSON(wechatTemplate);
        ResponseEntity<WechatTemplate> formWorkMsgS = restTemplate.postForEntity(formWorkMsg, weiMsg, WechatTemplate.class);
        /*String responseBody = "";
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/xml; charset=utf-8"), xml);
        Request request = new sun.misc.Request.Builder()
                .url(formWorkMsg)
                .post(requestBody)
                .build();
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            int status = response.code();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            logger.error("okhttp3 post error >> ex = {}", ExceptionUtils.getStackTrace(e));
        } finally {
            if (response != null) {
                response.close();
            }
        }*/
        JSONObject msgJson = JSONObject.parseObject(userMsgS);
        JSONObject formJson = JSONObject.parseObject(userFormS);
        /*JSONObject json = JSONObject.toJSON(mapdata);
        JSONObject formWorkJson = JSONObject.parseObject(formWorkMsgS);
        System.out.println(json + "~~~~~~~~~");
        JSONObject result = WeixinUtil.doPostStr(url, json.toString());
        JSONObject json_arr = JSONObject.fromObject(result);
        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new StringEntity(outstr, "utf-8"));
        try {
            HttpResponse response = builder.build().execute(httpPost);
            HttpEntity entity = response.getEntity();
            jsonObject = JSONObject.fromObject(EntityUtils.toString(entity, "utf-8"));
        }*/
        model.put("msgJson", msgJson);
        model.put("formJson", formJson);
        model.put("token", accessToken);
        model.put("wechatTemplate", wechatTemplate);
        model.put("weiMsg", weiMsg);
        model.put("formWorkMsgS", formWorkMsgS);
        return PREFIX + "token.html";
    }

    /*private String post(String url, String json, String contentType) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //HttpClient
        CloseableHttpClient client = httpClientBuilder.build();
        client = (CloseableHttpClient) wrapClient(client);
        HttpPost post = new HttpPost(url);
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            if (StringUtils.isBlank(contentType)) {
                s.setContentType("application/json");
            }
            s.setContentType(contentType);
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            HttpEntity entity = res.getEntity();
            String str = EntityUtils.toString(entity, "utf-8");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }*/

    /**
     * 插入数据
     */
    @RequestMapping(value = "/insert")
    @ResponseBody
    public void insert() {
        btyBankService.insert();
    }

    /**
     * 微信还款提醒
     */
    @PostMapping("repayment")
    public String repayment(ModelMap model) {
        //获取accessToken
        Dict dict = dictService.getOne(new QueryWrapper<Dict>().eq("code", "access_token"));
        String accessToken = "";
        if (ToolUtil.isNotEmpty(dict)) {
            accessToken = dict.getName();
        }

        String hkje = "";
        String lx = "";
        String name = "";
        String wxOpenId = "";

        //获取还款信息
        List<BtyBorrower> list = btyBorrowerService.borrowerList();
        for (BtyBorrower btyBorrower : list) {

            hkje = btyBorrower.getHkje();//还款本金
            lx = btyBorrower.getLx();//还款利息
            name = btyBorrower.getName();//还款人姓名
            wxOpenId = btyBorrower.getOpenid();//微信openID
            //System.out.println(hkje+"=="+lx +"--"+ name + "]]" + wxOpenId);
        }


//        String hkje = String.valueOf(list.get(1));//还款本金
//        String lx = String.valueOf(list.get(2));//还款利息
//        String name = String.valueOf(list.get(3));//还款人姓名
//        String wxOpenId = String.valueOf(list.get(4));//微信openID
//        System.out.println(hkje + "--" + lx + "++" + name + "=="  + wxOpenId);
        System.out.println(list);
        //System.out.println(hkje+"=="+lx +"--"+ name + "]]" + wxOpenId);


        //微信openID
        String openid = "oM18PwWQsdIP3QEKcWejL1tF3X8s";

        // 封装基础数据
        WechatTemplate wechatTemplate = new WechatTemplate();
        //模板ID
        wechatTemplate.setTemplate_id("a7pYJwow9WwCbS7sah2fZqFG9L52NpdQKvPoNCzMZBk");
        //接收者openid
        wechatTemplate.setTouser(openid);

        Map<String, TemplateData> mapdata = new HashMap<>();
        // 封装模板数据
        TemplateData first = new TemplateData();
        first.setValue("尊敬的xxx,您的账单如下:");
        first.setColor("#173177");
        mapdata.put("first", first);

        TemplateData keyword1 = new TemplateData();
        keyword1.setValue("2020-09-02 16:01:56");//user.getMobile()
        first.setColor("#173177");
        mapdata.put("keyword1", keyword1);

        TemplateData keyword2 = new TemplateData();
        keyword2.setValue("2020-08-01--2020-08-31");
        first.setColor("#173177");
        mapdata.put("keyword2", keyword2);

        TemplateData keyword4 = new TemplateData();
        keyword4.setValue("1000");
        first.setColor("#173177");
        mapdata.put("keyword3", keyword4);

//        TemplateData keyword5= new TemplateData();
//        keyword5.setValue("已取消");
//        first.setColor("#173177");
//        mapdata.put("keyword4", keyword5);

//        TemplateData keyword6= new TemplateData();
//        keyword6.setValue("菜品已卖光");
//        first.setColor("#173177");
//        mapdata.put("keyword5", keyword6);


        TemplateData keyword3 = new TemplateData();
        keyword3.setValue("请您及时还款.");
        keyword3.setColor("#173177");
        mapdata.put("remark", keyword3);
        wechatTemplate.setData(mapdata);
        //RestTemplate restTemplate = new RestTemplate();

        //获取用户基本信息
        String userMsg = "https://api.weixin.qq.com/cgi-bin/user/info?openid=" + openid + "&lang=zh_CN&access_token=" + accessToken;
        //获取用户列表
        String userForm = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
        //发送模板消息
        String formWorkMsg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;

        RestTemplate restTemplate = new RestTemplate();
        //获取用户基本信息
        String userMsgS = restTemplate.getForObject(userMsg, String.class);
        //获取用户列表
        String userFormS = restTemplate.getForObject(userForm, String.class);
        //发送模板消息
        JSONObject weiMsg = (JSONObject) JSONObject.toJSON(wechatTemplate);
        ResponseEntity<WechatTemplate> formWorkMsgS = restTemplate.postForEntity(formWorkMsg, weiMsg, WechatTemplate.class);

        //将用户基本信息转化为相应的JSONObject对象
        JSONObject msgJson = JSONObject.parseObject(userMsgS);
        //用户列表
        JSONObject formJson = JSONObject.parseObject(userFormS);


//        List<BtyBorrower> array = new ArrayList();
//        BtyBorrower btyBorrower = new BtyBorrower();
//        btyBorrower.setHkje("1010");
//        btyBorrower.setLx("1");
//        btyBorrower.setName("杨晓晨");
//        btyBorrower.setOpenid("oM18PwWQsdIP3QEKcWejL1tF3X8s");
//
//        BtyBorrower btyBorrowe = new BtyBorrower();
//        btyBorrowe.setHkje("1010");
//        btyBorrowe.setLx("1");
//        btyBorrowe.setName("陈书惠");
//        btyBorrowe.setOpenid("oM18PwQBM_f-4xlF7DKwnLQZ7XXc");
//
//        array.add(btyBorrower);
//        array.add(btyBorrowe);
//        array.add(btyBorrower);
//        System.out.println(array);
//
//        JSONObject msgJson = null ;
//        JSONObject formJson = null;
//        JSONObject weiMsg = null;
//        // 封装基础数据
//        WechatTemplate wechatTemplate = new WechatTemplate();
//        ResponseEntity<WechatTemplate> formWorkMsgS = null;
//
//        for (BtyBorrower btyBorrower1 : array) {
//
//            hkje = btyBorrower1.getHkje();//还款本金
//            lx = btyBorrower1.getLx();//还款利息
//            name = btyBorrower1.getName();//还款人姓名
//            wxOpenId = btyBorrower1.getOpenid();//微信openID
//
//
//            //模板ID
//            wechatTemplate.setTemplate_id("a7pYJwow9WwCbS7sah2fZqFG9L52NpdQKvPoNCzMZBk");
//            //接收者openid
//            wechatTemplate.setTouser(wxOpenId);
//
//            Map<String, TemplateData> mapdata = new HashMap<>();
//            // 封装模板数据
//            TemplateData first = new TemplateData();
//            first.setValue("尊敬的" + name + ",您的账单如下:");
//            first.setColor("#173177");
//            mapdata.put("first", first);
//
//            TemplateData keyword1 = new TemplateData();
//            keyword1.setValue("2020-09-02 16:01:56");//user.getMobile()
//            first.setColor("#173177");
//            mapdata.put("keyword1", keyword1);
//
//            TemplateData keyword2 = new TemplateData();
//            keyword2.setValue("2020-08-01--2020-08-31");
//            first.setColor("#173177");
//            mapdata.put("keyword2", keyword2);
//
//            TemplateData keyword4 = new TemplateData();
//            keyword4.setValue(hkje);
//            first.setColor("#173177");
//            mapdata.put("keyword3", keyword4);
//
////        TemplateData keyword5= new TemplateData();
////        keyword5.setValue("已取消");
////        first.setColor("#173177");
////        mapdata.put("keyword4", keyword5);
//
////        TemplateData keyword6= new TemplateData();
////        keyword6.setValue("菜品已卖光");
////        first.setColor("#173177");
////        mapdata.put("keyword5", keyword6);
//
//
//            TemplateData keyword3 = new TemplateData();
//            keyword3.setValue("请您及时还款.");
//            keyword3.setColor("#173177");
//            mapdata.put("remark", keyword3);
//            wechatTemplate.setData(mapdata);
//            //RestTemplate restTemplate = new RestTemplate();
//
//            //获取用户基本信息
//            String userMsg = "https://api.weixin.qq.com/cgi-bin/user/info?openid=" + wxOpenId + "&lang=zh_CN&access_token=" + accessToken;
//            //获取用户列表
//            String userForm = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + accessToken;
//            //发送模板消息
//            String formWorkMsg = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
//
//            RestTemplate restTemplate = new RestTemplate();
//            //获取用户基本信息
//            String userMsgS = restTemplate.getForObject(userMsg, String.class);
//            //获取用户列表
//            String userFormS = restTemplate.getForObject(userForm, String.class);
//            //发送模板消息
//             weiMsg = (JSONObject) JSONObject.toJSON(wechatTemplate);
//             formWorkMsgS = restTemplate.postForEntity(formWorkMsg, weiMsg, WechatTemplate.class);
//
//            //将用户基本信息转化为相应的JSONObject对象
//             msgJson = JSONObject.parseObject(userMsgS);
//            //用户列表
//             formJson = JSONObject.parseObject(userFormS);
//
//        }
//
//


        model.put("msgJson", msgJson);
        model.put("formJson", formJson);
        model.put("token", accessToken);
        model.put("wechatTemplate", wechatTemplate);
        model.put("weiMsg", weiMsg);
        model.put("formWorkMsgS", formWorkMsgS);
        return PREFIX + "token.html";
    }

    /**
     * webservice页面
     */
    @GetMapping("webservice")
    public String webservice() {
        return PREFIX + "webservice.html";
    }

    /**
     * 美团登入判断
     */
    @GetMapping("meiTuanSign")
    public String meiTuanSign() {
        return PREFIX + "meiTuan/meiTuanSign.html";
    }

    /**
     * 美团登入页面
     */
    @ResponseBody
    @PostMapping("judge")
    public String judge(String yaoMa) {
        String judge = meiTuanService.judge(yaoMa);
        if (judge != null && !"".equals(judge)) {
            return judge;
        }
        return "0";
    }

    /**
     * 美团录入页面
     */
    @GetMapping("meiTuanMsg")
    public String meiTuanMsg(String yaoMa, ModelMap map) {
        map.put("yaoMa", yaoMa);
        return PREFIX + "meiTuan/meiTuanMsg.html";
    }
    /**
     * 美团录入信息
     */
    @ResponseBody
    @PostMapping("insertMeiTuan")
    public Integer insertMeiTuan(MeiTuan meiTuan) {
        return meiTuanService.insertMeiTuan(meiTuan);
    }

    /**
     * 获取美团列表
     */
    @RequestMapping(value = "listMt")
    @ResponseBody
    public Object list(String condition, String sjh,String ym) {
        Page<Map<String, Object>> list;
        list=meiTuanService.list(condition,sjh,ym);
        Page<Map<String, Object>> wrap = new NoticeWrapper(list).wrap();
        return LayuiPageFactory.createPageInfo(wrap);
    }


}
